// CyTargetLinker,
// a Cytoscape plugin to extend biological networks with regulatory interaction
// Copyright 2011-2012 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package cytargetlinker;

import giny.model.Edge;
import giny.model.Node;
import giny.view.NodeView;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cytargetlinker.io.XgmmlParser;
import cytoscape.Cytoscape;
import cytoscape.view.CyNetworkView;

/**
 * this class handles the RINs
 * load a RIN
 * show or hide a RIN
 * 
 */
public class RINHandler {
	
	private static RINHandler handler;
	
	public static RINHandler getHandler() {
		if(handler == null) {
			handler = new RINHandler();
		}
		return handler;
	}
	
	private RINHandler() {
		xPosition = new HashMap<String, Double>();
		yPosition = new HashMap<String, Double>();
		removedNodes = new ArrayList<Node>();
		doNotRemove = new ArrayList<Node>();
	}
	
	/**
	 * loads and opens the rins
	 * TODO: allow other file types than xgmml
	 */
	public void loadNetworks(List<File> files, CyTargetLinker linker) {
		for(File file : files) {
			XgmmlParser parser = new XgmmlParser();
			RegulatoryInteractionNetwork network = new RegulatoryInteractionNetwork();
			try {
				parser.parseXgmmlFile(file, new ArrayList<String>(linker.getUserNetworkIds().keySet()));
				network.setName(parser.getNetworkName());
				network.setFile(file);
				network.setEdges(parser.getEdges());
				network.setNewInteractions(parser.getEdges().size());
				network.setEdgeType(parser.getNetworkProperties().get("Type"));
				if(network.getNewInteractions() == 0) {
					linker.setStatusMessage(linker.getStatusMessage() + network.getName() + " | " + "no matching regulatory interactions found.\n");
				} else {
					linker.setStatusMessage(linker.getStatusMessage() + network.getName() + " | " + network.getNewInteractions() + " regulatory interactions.\n");
					linker.getRegulatoryInteractionNetworks().add(network);
				}
			} catch (Exception e) {
				linker.setStatusMessage(linker.getStatusMessage() + "WARNING: An error occured when reading " + file.getName() + ". This RIN will not be included in the analysis.\n");
			} 
		}
		
		Collections.sort(linker.getRegulatoryInteractionNetworks());
		for(int j = 0; j < linker.getRegulatoryInteractionNetworks().size(); j++) {
			linker.getRegulatoryInteractionNetworks().get(j).setColor(Preferences.getInstance().getColors().get(j));
		}
	}
	
	/**
	 * hides all edges from one regulatory interaction network
	 * if there are not any other interactions for a new node
	 * then the node is hidden as well
	 */
	public void hideRIN(RegulatoryInteractionNetwork net, CyTargetLinker linker) {
		CyNetworkView view = Cytoscape.getNetworkView(linker.getResultingNetwork().getIdentifier());
		for (Node node : net.getCyNodes()) {
			String id = node.getIdentifier();
			if(removedNodes.contains(node)) {
				if (!net.getHiddenNodes().contains(node)) {
					net.getHiddenNodes().add(node);
				}
				net.getxPosition().put(id, xPosition.get(id));
				net.getyPosition().put(id, yPosition.get(id));
			} else {
				// check if other edge still points to the node
				boolean found = false;
				for (RegulatoryInteractionNetwork rin : linker.getRegulatoryInteractionNetworks()) {
					if (!rin.equals(net)) {
						if (rin.getCyNodes().contains(node) && !rin.getHiddenNodes().contains(node)) {
							found = true;
						}
					}
				}
				if (!net.getHiddenNodes().contains(node)) {
					NodeView nodeView = view.getNodeView(node);
					net.getxPosition().put(id, nodeView.getXPosition());
					net.getyPosition().put(id, nodeView.getYPosition());
				}
	
				if (!found && !net.getHiddenNodes().contains(node)) {
					linker.getResultingNetwork().hideNode(node.getRootGraphIndex());
				}
				if (!net.getHiddenNodes().contains(node)) {
					net.getHiddenNodes().add(node);
				}
			}
		}
		net.getCyNodes().removeAll(net.getHiddenNodes());

		for (Edge edge : net.getCyEdges()) {
			linker.getResultingNetwork().hideEdge(edge.getRootGraphIndex());
			net.getHiddenEdges().add(edge);
		}
		net.getCyEdges().clear();
		net.setHidden(true);
	}
	
	/**
	 * shows all the hidden edges and nodes from a RIN again
	 * @param net
	 */
	public void showRIN(RegulatoryInteractionNetwork net, CyTargetLinker linker) {
		CyNetworkView view = Cytoscape.getNetworkView(linker.getResultingNetwork().getIdentifier());
		for(Node node : net.getHiddenNodes()) {
			String id = node.getIdentifier();
			linker.getResultingNetwork().restoreNode(node.getRootGraphIndex()); 
            NodeView nodeView = view.getNodeView(node); 
            if(nodeView.getXPosition() == 10.0 && nodeView.getYPosition() == 10.0) {
                nodeView.setXPosition(net.getxPosition().get(id)); 
                nodeView.setYPosition(net.getyPosition().get(id));
            }
            net.getCyNodes().add(node);
		}
		net.getxPosition().clear();
		net.getyPosition().clear();
		net.getHiddenNodes().clear();
        
		for (Edge edge: net.getHiddenEdges()){ 
			linker.getResultingNetwork().restoreEdge(edge.getRootGraphIndex()); 
			net.getCyEdges().add(edge);
        } 
		net.setHidden(false);
		net.getHiddenEdges().clear();
		
		CyTargetLinkerVisualStyle style = new CyTargetLinkerVisualStyle();	
		Cytoscape.getNetworkView(linker.getResultingNetwork().getIdentifier()).applyVizmapper(style.createVisualStyle(linker));
		Cytoscape.createNetworkView(linker.getResultingNetwork(), "CyTargetLinkerView");
	}
	
	
	private Map<String, Double> xPosition; 
    private Map<String, Double> yPosition; 
    private List<Node> removedNodes;
    private List<Node> doNotRemove;
    
    public List<Node> getRemovedNodes() {
    	return removedNodes;
    }

	
	/**
	 * hides all interactions between two nodes if not
	 * enough RINs support the interaction
	 */
	public void applyThreshold(CyTargetLinker linker) {
		CyNetworkView view = Cytoscape.getNetworkView(linker.getResultingNetwork().getIdentifier());
		Map<String, List<Edge>> map = new HashMap<String, List<Edge>>();
		
		// check if a node is hidden - then it's not necessary anymore to remove it
		for(RegulatoryInteractionNetwork net : linker.getRegulatoryInteractionNetworks()) {
			if(net.isHidden()) {
				for(Node n : net.getHiddenNodes()) {
					if(removedNodes.contains(n)) {
						removedNodes.remove(n);
					}
				}
			}
		}
		
		// restore all removed nodes before applying the threshold
		for(Node node : removedNodes) {
			linker.getResultingNetwork().restoreNode(node.getRootGraphIndex()); 
            NodeView nodeView = view.getNodeView(node); 
            if(nodeView.getXPosition() == 10.0 && nodeView.getYPosition() == 10.0) {
                nodeView.setXPosition(xPosition.get(node.getIdentifier())); 
                nodeView.setYPosition(yPosition.get(node.getIdentifier()));
            }
		}
		
		removedNodes.clear();
		doNotRemove.clear();
		xPosition.clear();
		yPosition.clear();
		
		// restore all edges before applying the threshold
		for(RegulatoryInteractionNetwork net : linker.getRegulatoryInteractionNetworks()) {
			if(!net.isHidden()) {
				for(Edge e : net.getCyEdges()) {
					linker.getResultingNetwork().restoreEdge(e.getRootGraphIndex());
					String key = e.getSource().getIdentifier() + " - " + e.getTarget().getIdentifier();
					if(map.containsKey(key)) {
						map.get(key).add(e);
					} else {
						List<Edge> list = new ArrayList<Edge>();
						list.add(e);
						map.put(key, list);
					}
				}
			}
		}

		// go through map and hide all edges and nodes which 
		// are supported by less RINs than the threshold requires
		for(String str : map.keySet()) {
			if(map.get(str).size() < linker.getThreshold()) {
				for(Edge e : map.get(str)) {
					linker.getResultingNetwork().hideEdge(e.getRootGraphIndex());
					
					if(linker.getNewNodes().containsKey(e.getSource().getIdentifier())) {
						removeNode(e.getSource(), view);
					} else if (linker.getNewNodes().containsKey(e.getTarget().getIdentifier())) {
						removeNode(e.getTarget(), view);
					}
				}
			} else {
				for(Edge e : map.get(str)) {
					doNotRemove.add(e.getSource());
					doNotRemove.add(e.getTarget());
				}
			}
		}
		
		removedNodes.removeAll(doNotRemove);
		
		for(Node node : removedNodes) {
			linker.getResultingNetwork().hideNode(node.getRootGraphIndex());
		}
	}
	
	private void removeNode(Node node, CyNetworkView view) {
		if(!removedNodes.contains(node)) {
			removedNodes.add(node);
			NodeView nodeView = view.getNodeView(node);
			xPosition.put(node.getIdentifier(), nodeView.getXPosition());
			yPosition.put(node.getIdentifier(), nodeView.getYPosition());
		}
	}

}
